package de.melistik.smugmugsync;

import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JToolBar;

import com.kallasoft.smugmug.api.json.entity.Album;
import com.kallasoft.smugmug.api.json.entity.Category;

import de.melistik.IconHandler;
import de.melistik.smugmugsync.connect.SmugMugBaseRW;
import de.melistik.smugmugsync.connect.SmugMugConnection;
import de.melistik.smugmugsync.model.SyncFolder;
import de.melistik.smugmugsync.model.UsersPreferences;

@SuppressWarnings("serial")
public class GuiEntry extends JFrame {

	public static void main(String args[]) {
		new GuiEntry();
	}

	JFileChooser fileChooser = new JFileChooser();
	JLabel currentPath = new JLabel("");
	SyncFolderTableModel tableModel = new SyncFolderTableModel();
	FileFolderHandler fileFolderHandler = new FileFolderHandler(tableModel);

	JTable table = new JTable(tableModel);

	UsersPreferences pref = new UsersPreferences();
	SmugMugConnection connection = null;

	public GuiEntry() {
		this.setTitle("jSmugSync");
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setName("jSmugSync");
		this.setLayout(new BorderLayout());
		this.setLocationRelativeTo(null);
		this.setSize(
				(int) ((Toolkit.getDefaultToolkit().getScreenSize().width) * 0.7),
				(int) ((Toolkit.getDefaultToolkit().getScreenSize().height) * 0.7));
		this.setLocation(
				(Toolkit.getDefaultToolkit().getScreenSize().width / 2)
						- (this.getWidth() / 2), (Toolkit.getDefaultToolkit()
						.getScreenSize().height / 2) - (this.getHeight() / 2));
		this.setIconImage(IconHandler.fileManager.getImage());

		JMenuBar menubar = new JMenuBar();

		JMenu file = new JMenu("File");

		JMenuItem prefItem = new JMenuItem("Preferences", IconHandler.vcardEdit);
		prefItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				PreferencesDialog d = new PreferencesDialog(tableModel
						.getStartSyncFolder() != null ? tableModel
						.getStartSyncFolder().getAbsolutePath() : null);
				d.setVisible(true);
			}

		});

		file.add(prefItem);

		JMenuItem eMenuItem = new JMenuItem("Exit", IconHandler.keyEscape);
		eMenuItem.setToolTipText("Exit application");
		eMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				System.exit(0);
			}

		});

		file.add(eMenuItem);
		menubar.add(file);
		setJMenuBar(menubar);

		JToolBar topToolBar = new JToolBar("Top Toolbar");
		topToolBar.setFloatable(false);

		fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		JButton selectFolder = new JButton("Select SyncFolder",
				IconHandler.fileManager);
		selectFolder.setToolTipText("From where should the sync begin");
		selectFolder.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				int returnVal = fileChooser.showOpenDialog(GuiEntry.this);

				if (returnVal == JFileChooser.APPROVE_OPTION) {
					setStartSyncFolder(fileChooser.getSelectedFile());
				} else {
					System.out.println("Open command cancelled by user.");
				}
			}
		});
		topToolBar.add(selectFolder);
		topToolBar.add(currentPath);
		add(topToolBar, BorderLayout.NORTH);

		tableModel.initColumnSizes(table);
		table.setFillsViewportHeight(true);

		JScrollPane scrollPane = new JScrollPane(table);
		add(scrollPane, BorderLayout.CENTER);

		JToolBar toolBar = new JToolBar();
		toolBar.setFloatable(false);
		JButton smugMugCheck = new JButton("Check Selection With SmugMug");
		smugMugCheck.setIcon(IconHandler.smugmug);
		smugMugCheck.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				checkSelectionWithSmugMug();
			}
		});
		toolBar.add(smugMugCheck);
		JButton syncWithSmugMug = new JButton("Start Sync/Upload Process");
		syncWithSmugMug.setIcon(IconHandler.update);
		syncWithSmugMug.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				checkSelectionWithSmugMug();
				UploadDialog upload = new UploadDialog(connection,
						getCheckedSyncFolders());
				upload.setVisible(true);
			}
		});
		toolBar.add(syncWithSmugMug);
		add(toolBar, BorderLayout.SOUTH);

		setVisible(true);
		readSetting();
	}

	private void readSetting() {
		if (pref.readSettings()) {
			if (pref.getSyncStartPath() != null) {
				setStartSyncFolder(new File(pref.getSyncStartPath()));
			}
		}

	}

	private boolean checkConnection() {
		if (connection == null) {
			if (pref.getUsername() == null || pref.getPassword() == null) {
				JOptionPane
						.showMessageDialog(
								GuiEntry.this,
								"Please set before Username and Password in Preference-Screen (File->Preferences)");
			} else {
				connection = new SmugMugConnection(pref.getUsername(),
						pref.getPassword());
			}
		}
		if (connection != null && connection.getResponse().getUserID() == null) {
			JOptionPane
					.showMessageDialog(GuiEntry.this,
							"Not able to connect to SmugMug - please check Username/Password");
			return false;
		}
		return true;
	}

	private void checkSelectionWithSmugMug() {
		if (checkConnection()) {
			SmugMugBaseRW rw = new SmugMugBaseRW(connection);
			for (SyncFolder syncFoler : getCheckedSyncFolders()) {
				Category smugCat = rw.getCategoryByName(syncFoler
						.getCategoryName());
				if (smugCat != null) {
					syncFoler.setCategoryId(smugCat.getID());
					Album smugAlbum = rw.findAlbumInList(
							smugCat.getAlbumList(), syncFoler.getAlbumName(),
							smugCat.getID());
					if (smugAlbum != null) {
						syncFoler.setAlbumId(smugAlbum.getID());
						syncFoler.setFilesOnSmugMug(smugAlbum.getImageCount());
					} else {
						syncFoler.setAlbumId(-1);
					}
				} else {
					syncFoler.setCategoryId(-1);
					syncFoler.setAlbumId(-1);
				}
			}
			table.repaint();
		}
	}

	public List<SyncFolder> getCheckedSyncFolders() {
		List<SyncFolder> result = new ArrayList<SyncFolder>();
		for (SyncFolder syncFoler : tableModel.getSyncFolderList()) {
			if (syncFoler.isSyncEnabled()) {
				result.add(syncFoler);
			}
		}
		return result;
	}

	private void setStartSyncFolder(File startFolder) {
		tableModel.setStartSyncFolder(startFolder);
		if (tableModel.getStartSyncFolder() != null
				&& tableModel.getStartSyncFolder().getPath() != null) {
			currentPath.setText(tableModel.getStartSyncFolder().getPath());
			tableModel.getSyncFolderList().clear();
			tableModel.getSyncFolderList().addAll(
					fileFolderHandler.getSupportedFiles(new SyncFolder(
							tableModel.getStartSyncFolder())));
			table.repaint();
		}
	}

}
